
package com.joysuch.wwyt.mh.service.impl;

import cn.zlg.common.util.CollectionUtils;
import com.joysuch.wwyt.bp.enums.DataStateTypes;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.service.BaseAttachmentRepositoryService;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.mh.BizUtils;
import com.joysuch.wwyt.mh.bean.MhHazardChemProductBean;
import com.joysuch.wwyt.mh.bean.MhHazardChemicalProductSearchBean;
import com.joysuch.wwyt.mh.bean.MhMajorHazardChemProductBean;
import com.joysuch.wwyt.mh.entity.MhMajorHazardChemProduct;
import com.joysuch.wwyt.mh.entity.MhMajorHazardChemProductRel;
import com.joysuch.wwyt.mh.entity.dsl.QMhMajorHazardChemProduct;
import com.joysuch.wwyt.mh.repository.MhMajorHazardChemProductDao;
import com.joysuch.wwyt.mh.repository.MhMajorHazardChemProductRelDao;
import com.joysuch.wwyt.mh.service.MhHazardChemicalProductService;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
@Transactional
public class MhHazardChemicalProductServiceImpl implements MhHazardChemicalProductService {

    /*
     * private static final int SALT_SIZE = 8;
     * private CredentialsDigest credentialsDigest;
     */
    @Autowired
    private MhMajorHazardChemProductDao dao;
    @Autowired
    private MhMajorHazardChemProductRelDao relDao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;
    @Autowired
    private BaseAttachmentRepositoryService attachmentService;

    @Override
    public ResultBean findAll(Pageable pageable, MhHazardChemicalProductSearchBean searchBean) {
        pageable = PageDataUtils.addOrderByDesc(pageable, "createTime");
        QMhMajorHazardChemProduct qMhMajorHazardChemProduct = QMhMajorHazardChemProduct.mhMajorHazardChemProduct;
        Predicate predicate = qMhMajorHazardChemProduct.isNotNull();
        predicate = ExpressionUtils.and(predicate, qMhMajorHazardChemProduct.orgCode.like(Context.getCompanyCode() + "%"));
        predicate = ExpressionUtils.and(predicate, qMhMajorHazardChemProduct.tenentId.eq(Context.getCurrentTenantId()));
        predicate = ExpressionUtils.and(predicate, ExpressionUtils.or(qMhMajorHazardChemProduct.state.notIn(DataStateTypes.DELETE.getState()),
                qMhMajorHazardChemProduct.state.isNull()));
        predicate = StringUtils.isNotBlank(searchBean.getNameOrCAS()) ?
                ExpressionUtils.and(predicate,ExpressionUtils.or(qMhMajorHazardChemProduct.name.contains(searchBean.getNameOrCAS()),qMhMajorHazardChemProduct.casNo.contains(searchBean.getNameOrCAS()))) : predicate;
        Page<MhMajorHazardChemProduct> data = dao.findAll(predicate, pageable);
        Page<MhMajorHazardChemProductBean> page = PageDataUtils.convertPageData(data,
                new PageDataUtils.PageDataConvert<MhMajorHazardChemProductBean, MhMajorHazardChemProduct>() {
                    @Override
                    public MhMajorHazardChemProductBean convert(MhMajorHazardChemProduct f) {
                        MhMajorHazardChemProductBean m = new MhMajorHazardChemProductBean();
                        m.setAlias(f.getAlias());
                        m.setCasNo(f.getCasNo());
                        m.setCode(f.getCode());
                        m.setEngName(f.getEngName());
                        m.setId(f.getId());
                        m.setType(f.getType());
                        m.setOrgCode(f.getOrgCode());
                        m.setName(f.getName());
                        m.setHazardChemicalFlag(f.getHazardChemicalFlag());
                        m.setHazardChemicalFlagName(BizUtils.translateYesNoToChinese(f.getHazardChemicalFlag()));
                        if (f.getAttachmentId() != null) {
                            m.setAttachment(attachmentService.findByIdIntoBean(f.getAttachmentId()));
                        }
                        m.setMax(f.getMax());
                        m.setChemProductType(f.getChemProductType());
                        m.setStorageType(f.getStorageType());
                        m.setFunction(f.getFunctions());
                        m.setYearlyProductionCapacity(f.getYearlyProductionCapacity());
                        m.setGasYearlyProductionCapacity(f.getGasYearlyProductionCapacity());
                        m.setYearlyMax(f.getYearlyMax());
                        m.setGasYearlyMax(f.getGasYearlyMax());
                        return m;
                    }
                });

        return ResultBean.pageData(page.getContent(), page.getTotalElements());
    }

    @Override
    public void add(MhHazardChemProductBean mh) {
        MhMajorHazardChemProduct m = new MhMajorHazardChemProduct();
        String name = mh.getName();
        String code = mh.getCode();
        int count = dao.countByName(name);
        int countCode = dao.countByCode(code);
        if(countCode > 0){
            throw new IllegalArgumentException("此危化品编号已存在");
        }
        if (count > 0) {
            throw new IllegalArgumentException("此危化品名称已存在");
        }

        m.setId(mh.getId());
        m.setTenentId(mh.getTenentId());
        m.setOrgCode(mh.getOrgCode());
        m.setCode(mh.getCode());
        m.setName(name);
        m.setAlias(mh.getAlias());
        m.setEngName(mh.getEngName());
        m.setCasNo(mh.getCasNo());
        m.setType(mh.getType());
        m.setHazardChemicalFlag(mh.getHazardChemicalFlag());
        m.setCreateBy(mh.getCreateBy());
        m.setCreateTime(mh.getCreateTime());
        m.setUpdateBy(mh.getUpdateBy());
        m.setUpdateTime(mh.getUpdateTime());
        m.setDeleteFlag(mh.getDeleteFlag());
        m.setState(mh.getState());
        m.setAttachmentId(mh.getAttachmentId());
        m.setChemProductType(mh.getChemProductType());
        m.setFunctions(mh.getFunction());
        m.setMax(mh.getMax());
        m.setStorageType(mh.getStorageType());
        m.setYearlyProductionCapacity(mh.getYearlyProductionCapacity());
        m.setGasYearlyProductionCapacity(mh.getGasYearlyProductionCapacity());
        m.setYearlyMax(mh.getYearlyMax());
        m.setGasYearlyMax(mh.getGasYearlyMax());
        // mhHazardChemicalProduct.setState(DataStateTypes.EFFECTIVE.getState());
        if (mh.getCode() != null && !"".equals(mh.getCode())) {
            m = dao.save(m);
        } else {
            m.setCode(bizCodeGeneratorFacade.weiXianHuaXuePin());
            m = dao.save(m);
        }
        this.checkCasNo(m);
    }

    private void checkCasNo(MhMajorHazardChemProduct m) {
        int num = dao.countByCasNo(m.getCasNo());
        if (num > 1) {
            throw new IllegalArgumentException("CAS号已存在");
        }
    }

    @Override
    public void edit(MhHazardChemProductBean mhHazardChemicalProduct) {
        String name = mhHazardChemicalProduct.getName();
        String code = mhHazardChemicalProduct.getCode();
        //MhMajorHazardChemProduct one = dao.getOne(mhHazardChemicalProduct.getId());
        MhMajorHazardChemProduct one = dao.findById(mhHazardChemicalProduct.getId()).orElseThrow(() -> new IllegalArgumentException("危化品不存在"));
        if (!code.equals(one.getCode())) {
            int countCode = dao.countByCode(code);
            if (countCode > 0) {
                throw new IllegalArgumentException("此危化品编号已存在");
            }
        }
        if (!name.equals(one.getName())) {
            int count = dao.countByName(name);
            if (count > 0) {
                throw new IllegalArgumentException("此危化品名称已存在");
            }
        }

        one.setCode(mhHazardChemicalProduct.getCode());
        one.setId(mhHazardChemicalProduct.getId());
        one.setCasNo(mhHazardChemicalProduct.getCasNo());
        one.setHazardChemicalFlag(mhHazardChemicalProduct.getHazardChemicalFlag());
        one.setName(mhHazardChemicalProduct.getName());
        one.setEngName(mhHazardChemicalProduct.getEngName());
        one.setType(mhHazardChemicalProduct.getType());
        one.setAlias(mhHazardChemicalProduct.getAlias());
        one.setOrgCode(mhHazardChemicalProduct.getOrgCode());
        one.setAttachmentId(mhHazardChemicalProduct.getAttachmentId());
        one.setMax(mhHazardChemicalProduct.getMax());
        one.setStorageType(mhHazardChemicalProduct.getStorageType());
        one.setFunctions(mhHazardChemicalProduct.getFunction());
        one.setChemProductType(mhHazardChemicalProduct.getChemProductType());
        one.setYearlyProductionCapacity(mhHazardChemicalProduct.getYearlyProductionCapacity());
        one.setGasYearlyProductionCapacity(mhHazardChemicalProduct.getGasYearlyProductionCapacity());
        one.setYearlyMax(mhHazardChemicalProduct.getYearlyMax());
        one.setGasYearlyMax(mhHazardChemicalProduct.getGasYearlyMax());
        one = dao.save(one);
        this.checkCasNo(one);
    }

    @Override
    public void delete(Long id) {
        MhMajorHazardChemProduct product = dao.findById(id).orElseThrow(() -> new IllegalArgumentException("危化品不存在"));
        List<MhMajorHazardChemProductRel> list = relDao.findByMhMajorHazardChemProduct(product);
        if (CollectionUtils.isNotEmpty(list)) {
            throw new IllegalArgumentException("请先删除危险源与危化品的绑定关系");
        }
        product.setState(DataStateTypes.DELETE.getState());
        dao.save(product);

//        //      relDao.deleteByMhMajorHazardChemProduct(dao.getOne(id));
//        dao.deleteById(id);
    }

    /**
     * 危化品查看
     *
     * @param id
     * @return
     */
    @Override
    public MhMajorHazardChemProductBean findById(Long id) {
        MhMajorHazardChemProduct product = dao.findById(id).orElseThrow(() -> new IllegalArgumentException("危化品不存在"));
        return this.product2Bean(product);
    }

    private MhMajorHazardChemProductBean product2Bean(MhMajorHazardChemProduct f) {
        MhMajorHazardChemProductBean m = new MhMajorHazardChemProductBean();
        m.setAlias(f.getAlias());
        m.setCasNo(f.getCasNo());
        m.setCode(f.getCode());
        m.setEngName(f.getEngName());
        m.setId(f.getId());
        m.setType(f.getType());
        m.setOrgCode(f.getOrgCode());
        m.setName(f.getName());
        m.setHazardChemicalFlag(f.getHazardChemicalFlag());
        m.setHazardChemicalFlagName(BizUtils.translateYesNoToChinese(f.getHazardChemicalFlag()));
        if (f.getAttachmentId() != null) {
            m.setAttachment(attachmentService.findByIdIntoBean(f.getAttachmentId()));
        }
        m.setMax(f.getMax());
        m.setChemProductType(f.getChemProductType());
        m.setStorageType(f.getStorageType());
        m.setFunction(f.getFunctions());
        m.setYearlyProductionCapacity(f.getYearlyProductionCapacity());
        m.setGasYearlyProductionCapacity(f.getGasYearlyProductionCapacity());
        m.setYearlyMax(f.getYearlyMax());
        m.setGasYearlyMax(f.getGasYearlyMax());
        return m;
    }

}
